var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const { expressjwt: expressJWT } = require('express-jwt')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var indexViewRouter = require('./routes/csy/index')
var jwhRouter = require('./routes/jwh/jwh')
var cors = require('cors')
var app = express();
app.use(cors())

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(
  expressJWT({ secret: 'weiwei', algorithms: ['HS256'] }).unless({
    path: ['/csy/login', '/csy/refresh', '/csy/faceLogin', '/csy/yzmLogin',
      '/uploads', '/csy/send-sms', '/csy/register', '/csy/updatePassword',
      '/csy/faceBind', '/csy/captcha']
  })
)

// app.use(bodyparser.json({ limit: '10mb' }))
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/csy', indexViewRouter);
app.use('/jwh', jwhRouter);

//配置中间件，错误捕获
app.use(function (err, req, res, next) {
  //token解析失败
  const authorization = req.headers['authorization'];
  if (!authorization) {
    return res.status(401).send({ code: 401, msg: '请先登录' })
  }
  if (err.name === 'UnauthorizedError') {
    return res.status(401).send({
      code: 401,
      msg: 'token已过期,请重新登录'
    })
  }
})


// catch 404 and forward to error handler
app.use((req, res) => {
  res.status(404).json({ message: 'Not Found' });
});

// error handler
app.use((err, req, res) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Internal Server Error' });
});

module.exports = app;
